from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
import json
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication
from rest_framework.generics import ListAPIView
from rest_framework_simplejwt.authentication import JWTAuthentication

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet

from bowen.models import Bowen
from bowen.serializer import BowenSerializer
from rest_framework.parsers import MultiPartParser, FormParser
from houtai.models import YongHu
from houtai.serializer import HouTaiContentSerializer, HouTaiSerializer
# import base64
# import requests
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from houtai.utils.image import Image


# Create your views here.

# class Login(View):
#     """
#     简单注册代码
#     """
#     def post(self,request):
#         user=json.loads(request.body.decode('utf-8'))
#         username = user['username']
#         password = user['password']
#         try:
#             YongHu.objects.create_user(username=username, password=password)
#         except :
#             return  JsonResponse({'mag':'注册失败'}, status=201)
#         return JsonResponse({'mag':'注册成功'}, status=200)

class HouTaiList(ListAPIView):
    queryset = Bowen.objects.all()
    serializer_class = HouTaiSerializer
    permission_classes = (IsAuthenticated,)


class HouTai(ModelViewSet):
    queryset = Bowen.objects.all()
    serializer_class = HouTaiContentSerializer
    # authentication_classes = (JWTAuthentication,)
    permission_classes = (IsAuthenticated,)







class UpLoadImg(APIView):
    parser_classes = [MultiPartParser, FormParser]  # 用于解析 multipart/form-data 类型的请求内容
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        file = request.FILES['image']
        # res = file.read()
        # print(res)
        # print(file_content)
        # return Response({'ok':'1'})

        # with open("utils/config.json", "r") as f:
        #     config = json.load(f)
        # print(type(file.name))
        #
        #
        # print(gitee_api_url)
        # GitHub API 请求体
        # data = {
        #     "access_token": gitee_token,
        #     "message": f"Upload {file.name}",
        #     "content": base64.b64encode(file_content).decode("utf-8"),
        #     "branch": branch
        # }
        #
        # # 发起请求
        # headers = {"Authorization":gitee_token}
        # response = requests.post(gitee_api_url,headers=headers, data=data)
        # print(response.status_code)
        res = Image(file)
        response = res.image()
        if response.status_code == 201:  # 上传成功
            url = f"https://gitee.com/{res.owner}/{res.repo}/raw/{res.branch}/image/{file.name}"
            return Response({"url": url}, status=201)
        else:  # 上传失败
            return Response({"error": response.json()}, status=400)

    def delete(self, request,pk):
        # print(pk)
        data = Bowen.objects.get(id=pk)
        # print(data.imgurl)
        res = Image(data.imgurl)
        response = res.delete()
        if response.status_code == 200:  # 上传成功
            Bowen.objects.filter(id=pk).delete()
            if Bowen.objects.filter(id=pk).exists():
                return Response({"error": '删除失败'}, status=400)
            else:
                xinxi = '照片已删除'
                return Response({"xinxi": xinxi}, status=201)
        else:  # 删除失败
            return Response({"error": '删除失败'}, status=400)
